package com.guigu.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guigu.eduservice.entity.DetectionReport;
import com.guigu.eduservice.entity.DetectionReportImage;
import com.guigu.eduservice.mapper.DetectionReportImageMapper;
import com.guigu.eduservice.entity.Equipment;
import com.guigu.eduservice.entity.EquipmentType;
import com.guigu.eduservice.mapper.DetectionReportMapper;
import com.guigu.eduservice.mapper.EquipmentMapper;
import com.guigu.eduservice.mapper.EquipmentTypeMapper;
import com.guigu.eduservice.service.DetectionReportService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import com.guigu.eduservice.vo.DetectionReportVo;
import com.guigu.eduservice.vo.EqVo;
import com.guigu.eduservice.vo.EvaluationInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 检测报告表（存储设备检测的结果及结论） 服务实现类
 * </p>
 *
 * @author janecraft
 * @since 2025-09-27
 */
@Service
public class DetectionReportServiceImpl extends ServiceImpl<DetectionReportMapper, DetectionReport> implements DetectionReportService {

    @Autowired
    private DetectionReportMapper detectionReportMapper;
    @Autowired
    private EquipmentMapper equipmentMapper;
    @Autowired
    private EquipmentTypeMapper equipmentTypeMapper;
    @Override
    public boolean createDetectionReport(DetectionReportVo reportVo) {
        DetectionReport report = new DetectionReport();
        report.setEquipmentId(reportVo.getEquipmentId());
        report.setBusinessmanId(reportVo.getBusinessmanId());
        report.setAppearanceDetection(reportVo.getAppearanceDetection());
        report.setComponentFunctionDetection(reportVo.getComponentFunctionDetection());
        report.setPerformanceParameterDetection(reportVo.getPerformanceParameterDetection());
        report.setDetectionConclusion(reportVo.getDetectionConclusion());
        report.setAuditStatus(reportVo.getAuditStatus());
        report.setDetectionTime(LocalDateTime.now());

        boolean result = this.save(report);
        return result;
    }

    /**
     * 分页查询检测报告
     * @param pageNum 页码
     * @param pageSize 每页条数
     * @return 分页结果
     */
    @Override
    public PageInfo<EvaluationInfoVo> getEvaluationInfoList(DetectionReportVo vo, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        QueryWrapper<DetectionReport> wrapper = new QueryWrapper<>();
        if (vo.getAuditStatus() != null){
            wrapper.eq("audit_status",vo.getAuditStatus());
        }
        List<DetectionReport> detectionReportList = detectionReportMapper.selectList(wrapper);
        List<EvaluationInfoVo> voList = new ArrayList<>();

        for (DetectionReport detectionReport : detectionReportList) {
            Long equipmentId = detectionReport.getEquipmentId();
            Equipment equipment = equipmentMapper.selectById(equipmentId);
            EvaluationInfoVo evalVo = new EvaluationInfoVo();
            evalVo.setId(equipment.getEquipmentId());

            // 查询设备类型名称
            String equipmentTypeName = "未知";
            if (equipment.getTypeId() != null) {
                EquipmentType type = equipmentTypeMapper.selectById(equipment.getTypeId());
                if (type != null) {
                    equipmentTypeName = type.getTypeName();
                }
            }
            evalVo.setEquipmentTypeBrand(equipmentTypeName + "-" + equipment.getBrand());
            evalVo.setYear(equipment.getYear());
            evalVo.setWorkVolume("工作方量：" + equipment.getHour());
            evalVo.setUserName("用户" + equipment.getUserId());
            evalVo.setAssessmentPrice(equipment.getPrice()); // 单位：万元
            evalVo.setAuditStatus(detectionReport.getAuditStatus());

            // 获取检测报告，并添加检测状态条件
            LambdaQueryWrapper<DetectionReport> reportQueryWrapper = new LambdaQueryWrapper<DetectionReport>()
                    .eq(DetectionReport::getEquipmentId, equipment.getEquipmentId());

            // 如果传入了检测状态参数，则添加该条件
            if (vo.getAuditStatus()!= null) {
                reportQueryWrapper.eq(DetectionReport::getAuditStatus, vo.getAuditStatus());
            }

            DetectionReport report = detectionReportMapper.selectOne(reportQueryWrapper);

            if (report != null) {
                StringBuilder evalInfo = new StringBuilder();
                evalInfo.append("垂直高度：").append(equipment.getVerticalHeight()).append("<br>");
                evalInfo.append("支腿形式：").append(equipment.getOutriggerType()).append("<br>");
                evalInfo.append("底盘桥数：").append(equipment.getChassisAxle()).append("<br>");
                evalInfo.append("底盘排放：").append(equipment.getEmissionStandard()).append("<br>");
                evalInfo.append("检测时间：").append(report.getDetectionTime());

                evalVo.setEvaluationInfo(evalInfo.toString());
            } else {
                evalVo.setEvaluationInfo("暂无检测报告");
            }

            voList.add(evalVo);
        }
        return new PageInfo<>(voList);
    }
    @Autowired
    private DetectionReportImageMapper detectionReportImageMapper;
    //根据用户ID查询检测表以及检测表的图片
    @Override
    public DetectionReport selectDetectionReportById(Long equipmentId) {
        //根据设备ID拿到检测报告
        LambdaQueryWrapper<DetectionReport> wrapper = new LambdaQueryWrapper<>();
        if (equipmentId != null){
            wrapper.eq(DetectionReport::getEquipmentId,equipmentId);
        }else {
            return null;
        }
        DetectionReport one = detectionReportMapper.selectOne(wrapper);
        if (one == null || one.getReportId() == null){
            return null;
        }
        LambdaQueryWrapper<DetectionReportImage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DetectionReportImage::getReportId,one.getReportId());
        List<DetectionReportImage> images = detectionReportImageMapper.selectList(queryWrapper);
        //图片集合非空处理（避免set为null，前端遍历报错）
        one.setDetectionReportImages( images != null ? images : Collections.emptyList());
        return one;
    }

    /**
     * 修改检测报告审核状态
     * @param reportVo
     * @return
     */
    @Override
    public int updateDetectionReport(DetectionReportVo reportVo) {
        DetectionReport detectionReport = detectionReportMapper.selectById(reportVo.getReportId());
        detectionReport.setAuditStatus(reportVo.getAuditStatus());
        detectionReport.setAuditRemark(reportVo.getAuditRemark());
        detectionReport.setAuditTime(LocalDateTime.now());
        return detectionReportMapper.updateById(detectionReport);
    }


}
